package cn.edu.zstu.qingzhu.qingzhushop.controller.admin;


import cn.edu.zstu.qingzhu.qingzhushop.controller.BaseRestController;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Goods;
import cn.edu.zstu.qingzhu.qingzhushop.entity.GoodsQueryDTO;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.GoodsMapper;
import cn.edu.zstu.qingzhu.qingzhushop.service.IGoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/goods")
@Api(tags = "商品管理接口")
@CrossOrigin(origins={"*"}, methods={RequestMethod.GET, RequestMethod.POST})
public class GoodsManagerController  extends BaseRestController<IGoodsService, Goods,Integer> {

    @Autowired
    IGoodsService iGoodsService;
    @Autowired
    GoodsMapper goodsMapper;

    /**
     * 获取所有商品
     * @return
     */
    @RequestMapping(value = {"/list"},method = {RequestMethod.GET})
    public ResponseBean listGoods() {
        List<Goods> goodsList = iGoodsService.list();
        return ResponseBean.success("goods", goodsList);
    }

    /**
     * 获取所有商品id
     * @return
     */
    @RequestMapping(value = {"/listid"},method = {RequestMethod.GET})
    public ResponseBean listGoodsId() {
        List<Integer> goodsIdList = iGoodsService.listAllGoodsId();
        return ResponseBean.success("goodsId", goodsIdList);
    }


    /**
     * 分页查询分类获取商品信息
     * @param page
     * @param size
     * @param categoryid
     * @return
     */
    @RequestMapping(value = {"/queryByCategoryId"},method = {RequestMethod.GET})
    public ResponseBean searchPageByCategoryId(@ApiParam(name = "page",value = "页数")
                                               @RequestParam(value = "page", defaultValue = "1") Integer page,
                                               @ApiParam(name = "size",value = "记录数")
                                               @RequestParam(value = "limit", defaultValue = "20") Integer size,
                                               @ApiParam(name = "categoryId",value = "分类id")
                                               @RequestParam(value = "categoryId",required = false) Integer  categoryid) {
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper();
        Page<Goods> pageid = new Page<>(page, size);
        if (null != categoryid) {
            log.debug(categoryid.toString());
            goodsQueryWrapper.eq("goods_category",categoryid);
        }
        Page<Goods> result = goodsMapper.selectPage(pageid, goodsQueryWrapper);
        return ResponseBean.success("查询成功", result);
    }
    /**
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = {"/page"},method = {RequestMethod.GET})
    public ResponseBean pageGoods(@ApiParam(name = "page",value = "页数")
                          @RequestParam(name = "page",defaultValue = "1") Integer page,
                          @ApiParam(name = "size",value = "记录数")
                          @RequestParam(name = "size",defaultValue = "8") Integer size) {
        return ResponseBean.success(iGoodsService.page(new Page<>(page,size)));
    }
    /**
     * 分页查询
     * @param goodsQueryDTO 查询模型
     * @return
     */
    @RequestMapping(value = {"/query"},method = {RequestMethod.GET})
    public Object searchPage(@ApiParam(name = "queryModel",value = "查询模型") GoodsQueryDTO goodsQueryDTO) {
        log.debug(String.valueOf(goodsQueryDTO));
        return ResponseBean.success("查询成功",
                iGoodsService.page(goodsQueryDTO.getQueryModel().newPage(),
                        goodsQueryDTO.generate()));
    }

    //上传商品图片-1
    
    @PostMapping(value = "/img/upload")
    @ResponseBody
    public ResponseBean imgUpload(@RequestParam(value="img",required = false) MultipartFile file,
                                  @RequestParam(value = "id",required = true) Integer id,
                                  HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return ResponseBean.error();
        }
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(File.separator) + 1);  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        //图片访问的URI
        String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/imgs/";
        //文件临时存储位置,项目重启后会消失，因为是spring boot内置的Tomcat容器
        String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "imgs";
        // 新文件名
        fileName = UUID.randomUUID() + suffixName;
        String destFileName = path + File.separator+fileName;
        System.out.println("文件路径为:"+destFileName);
        File dest = new File(destFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            //文件复制
            String projectPath = System.getProperty("user.dir");
            String src = destFileName;
            //根据自己系统的resource 目录所在位置进行自行配置
            String destDir = "E:"+File.separator+"IntellijProject"+File.separator+"qingzhu_mall"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"upload"+File.separator+"imgs"+File.separator;
            copyFile(src,destDir,fileName);
            //将图片url写入数据库
            String url = "/qingzhu/upload/imgs/" + fileName;
            iGoodsService.updateGoodsPicURL(id,url);
            return ResponseBean.success();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseBean.error();
        }
    }



    private void copyFile(String src,String destDir,String fileName) throws IOException{
        FileInputStream in=new FileInputStream(src);
        File fileDir = new File(destDir);
        if(!fileDir.isDirectory()){
            fileDir.mkdirs();
        }
        File file = new File(fileDir,fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream out=new FileOutputStream(file);
        int c;
        byte buffer[]=new byte[1024];
        while((c=in.read(buffer))!=-1){
            for(int i=0;i<c;i++){
                out.write(buffer[i]);
            }
        }
        in.close();
        out.close();
    }

}
